package com.ruoyi.program.controller;

import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.program.service.ICreateNameOrderService;

import io.netty.util.internal.ObjectUtil;
import io.swagger.models.auth.In;

import com.ruoyi.program.domain.CreateNameOrder;
import com.ruoyi.common.annotation.Anonymous;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.AlipayConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.SignParams;
import com.alipay.api.domain.SignMerchantParams;
import com.alipay.api.domain.AccessParams;
import com.alipay.api.domain.PeriodRuleParams;

@Anonymous
@RestController
public class createNameOrderController {

  @Autowired
  private ICreateNameOrderService createNameOrderService;

  @PostMapping("/alipayapi/api/createNameOrder")
  // 由于 CommonResult 无法解析，将返回类型修改为 Map<String, Object>
  public Map<String, Object> createNameOrder(@RequestBody Map<String, String> requestBody) {
    System.out.println("requestBody" + requestBody);
    java.util.Map<String, Object> result = new java.util.HashMap<>();
    // 获取用户传入的参数
    String name = requestBody.get("surname");
    String sex = requestBody.get("sex");
    String type = requestBody.get("type");
    String birthday = requestBody.get("birthday");
    String userId = requestBody.get("userId");
    String appid = requestBody.get("appid");
    String subject = requestBody.get("subject");
    String remarks = requestBody.get("remarks");
    String contact = requestBody.get("contact");
    Integer productType = Integer.parseInt(requestBody.get("productType"));
    // 修改前
    // Integer productPrice = Integer.parseInt(requestBody.get("productPrice"));
    // 修改后
    Double productPrice = Double.parseDouble(requestBody.get("productPrice"));
    if (productType == 2) {
      // productType为2时，contact不能为空
      if (contact == null || contact.trim().isEmpty()) {
        result.put("success", false);
        result.put("message", "当商品类型为定制商品时，联系方式不能为空");
        return result;
      }
    } else {
      // productType为1时，即使没有contact也可以，设置为空字符串以避免数据库null错误
      contact = "";
    }

    CreateNameOrder createNameOrder = new CreateNameOrder();

    // 把用户传入的参数赋值给 createNameOrder 对象
    createNameOrder.setSurname(name);
    createNameOrder.setSex(Integer.parseInt(sex));
    createNameOrder.setType(Integer.parseInt(type));
    createNameOrder.setUserId(userId);
    createNameOrder.setAppid(appid); // 接收用户传入的 appid 参数，并赋值给 createNameOrder 的 appid 属性
    createNameOrder.setSubject(subject); // 商品标题
    createNameOrder.setRemarks(remarks); // 备注
    createNameOrder.setContact(contact); // 联系方式
    createNameOrder.setProductType(productType); // 商品类型 1普通商品 2定制商品
    createNameOrder.setProductPrice(productPrice.doubleValue()); // 商品价格
    // createNameOrder.setSubject(productTitle); // 设置订单标题
    // 移除原有的 java.sql.Date.valueOf 调用
    // createNameOrder.setBirthday(java.sql.Date.valueOf(birthday));

    // 假设用户传入的格式是 "yyyy-MM-dd HH:mm:ss"，可以使用 SimpleDateFormat 类将其转换为 Date 类型
    try {
      java.util.Date date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(birthday);
      // 假设 DateTimeExample.formatDateTime 方法需要的是字符串类型，先将 Date 转换为指定格式的字符串

      // 修改为使用 java.sql.Timestamp
      createNameOrder.setBirthday(new java.sql.Timestamp(date.getTime()));
    } catch (java.text.ParseException e) {
      e.printStackTrace();
      // 可以在这里添加错误处理逻辑，例如返回错误信息给用户
      result.put("code", 500);
      result.put("message", "日期格式解析错误，请使用 yyyy-MM-dd HH:mm:ss 格式");
      return result;
    }

    // 这里可以添加调用服务层方法创建订单的逻辑，并将结果放入 result 中
    int orderResult = createNameOrderService.createNameOrderService(createNameOrder);

    // 初始化 SDK 配置
    AlipayConfig alipayConfig = getAlipayConfig();
    AlipayClient alipayClient = null;

    try {
      alipayClient = new DefaultAlipayClient(alipayConfig);
    } catch (AlipayApiException e) {
      System.err.println("初始化 AlipayClient 失败：" + e.getMessage());
      e.printStackTrace();
      result.put("code", 500);
      result.put("message", "初始化支付宝客户端失败");
      return result;
    }

    // 构造请求参数
    AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
    AlipayTradeCreateModel model = new AlipayTradeCreateModel();

    // 设置订单基本信息
    model.setOutTradeNo(createNameOrder.getOrderNo()); // 商户订单号
    model.setTotalAmount(String.valueOf(createNameOrder.getTotalPrice())); // 订单总金额
    model.setSubject(createNameOrder.getSubject()); // 订单标题
    String product_code = "JSAPI_PAY"; // 当面付
    model.setProductCode(product_code); // 小程序支付中
    model.setOpAppId(appid); // 小程序ID
    model.setBuyerId(userId); // 买家支付宝用户ID

    // 设置签约参数
    SignParams agreementSignParams = new SignParams();
    SignMerchantParams subMerchant = new SignMerchantParams();
    subMerchant.setSubMerchantId(appid);
    agreementSignParams.setSubMerchant(subMerchant);
    AccessParams accessParams = new AccessParams();
    accessParams.setChannel("ALIPAYAPP");
    agreementSignParams.setAccessParams(accessParams);
    PeriodRuleParams periodRuleParams = new PeriodRuleParams();
    agreementSignParams.setPeriodRuleParams(periodRuleParams);
    // 由于 SignParams 类没有 setNotifyUrl 方法，推测应将通知地址设置到请求对象中
    String signNotifyUrl = "https://api.qqorw.com/prod-api/alipayapi/api/notify";
    agreementSignParams.setSignNotifyUrl(signNotifyUrl);
    model.setAgreementSignParams(agreementSignParams);

    // 设置请求模型
    request.setNotifyUrl("https://api.qqorw.com/prod-api/alipayapi/api/notify");
    request.setBizModel(model);

    // 执行请求
    try {
      AlipayTradeCreateResponse response = alipayClient.execute(request);
      if (response != null) {
        if (response.isSuccess()) {
          System.out.println("返回订单号：" + response.getBody());

          System.out.println("调用成功");
          result.put("code", 200);
          result.put("message", "订单创建成功且已发送给支付宝");

          // 获取支付宝返回的参数
          String alipayTradeNo = response.getTradeNo(); // 支付宝交易号
          String orderNo = createNameOrder.getOrderNo(); // 商家订单号

          System.out.println("支付宝交易号：" + alipayTradeNo + "商家订单号：" + orderNo);
          // 把支付宝交易号插入数据库中
          int code = createNameOrderService.updateAlipayTradeNoService(alipayTradeNo, orderNo);
          System.out.println("code" + code);

          // createNameOrderService.createNameOrderService();
          java.util.Map<String, Object> data = new java.util.HashMap<>();
          data.put("orderResult", orderResult);
          data.put("surname", createNameOrder.getSurname()); // 姓氏
          data.put("sex", createNameOrder.getSex()); // 姓氏
          data.put("birthday", createNameOrder.getBirthday()); // 生日
          data.put("type", createNameOrder.getType()); // 地址
          data.put("productOriginalPrice", createNameOrder.getProductOriginalPrice()); // 地址
          // data.put("type", createNameOrder.getType()); //原价
          // data.put("userId", createNameOrder.getUserId()); //现价

          data.put("subject", createNameOrder.getSubject()); // 商品名称
          data.put("appid", createNameOrder.getAppid()); // appid
          data.put("orderNo", createNameOrder.getOrderNo()); // 商家订单号
          data.put("productPrice", createNameOrder.getTotalPrice()); // 商品价格
          data.put("tradeNO", alipayTradeNo); // 支付宝交易号
          result.put("data", data);
        } else {
          System.out.println("调用失败");
          result.put("code", 500);
          result.put("message", "订单创建成功，但发送给支付宝失败");
          // 如果需要诊断链接（sdk版本是"4.38.0.ALL"及以上）
          // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
          // System.out.println("诊断链接：" + diagnosisUrl);
        }
      }
    } catch (AlipayApiException e) {
      System.err.println("调用支付接口失败：" + e.getMessage());
      e.printStackTrace();
      result.put("code", 500);
      result.put("message", "订单创建成功，但调用支付宝接口失败");
    }

    // 确保方法最后返回 result 对象
    return result;
  }

  @PostMapping("/alipayapi/api/querySurname")
  public Map<String, Object> querySurname(@RequestBody Map<String, String> requestBody) {

    System.out.println("requestBody" + requestBody);
    String surname = requestBody.get("surname");
    // 修改接收变量的类型
    String createNameOrder = createNameOrderService.querySurname(surname);
    System.out.println("createNameOrder" + createNameOrder);
    // 后续可以根据需要处理 createNameOrder 对象
    java.util.Map<String, Object> result = new java.util.HashMap<>();
    if (createNameOrder != null) {
      // 示例：将订单状态放入结果中
      result.put("status", createNameOrder);
    }
    return result;
  }

  // 假设 AlipayConfig 类存在于 com.alipay.api.config 包下，导入该类
  private static AlipayConf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u/X5PmQj5cdghQN57FB5N4pPNwKBgFQVWBGrh7r9xR1jFh1GDHnUiq8kU3qZk1A3wJSOQSTuIV9q9jIFt30gG/lzJL3Qes/MCC7nMd/mBeuInuHdXTKFtVgqDyCGICZmRoZozPw44+nnfdUnDbqf8Xp8KF6W02zKukL2G/kLnHrxcQlcZgJUh7S82iKGoxEnjGxkk665AoGAdfwvxGOFky2Yod0DwIBDj+gkSjWbe66gI5uK34WIVGIk8dLjb6mAL/zoijKnomlIaaCqECYfAMn1Hhorrfd61AxwgykzMVKzoP1wDHqHMM952TmlvggPEFySzdzJDN/IYaDDcISB+LDWsRuOlajeOOWDhOccoH6mMOKJweC7fjMCgYBjKJyRBpbwnoizj2Y2bT6NtX6yhytLGgnzSwhfmWOC3XDPC4PLn84ZgeSmGJd3P9YxA02pabakcgoMMfG5ovCGJ0SGzoRYoNtd5zXZsOnfVpKgC5rvwfp+/SRW8kkw/+Fvoe/ay+b48W+ztAHT/hGVHcajikwQYWZal02njBCi1A==";
    String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr5CdSBsNS5muGAl8pRGqEhZHm/Y5LVqcrCDNsUl5zTweYt3waaaG3tuk7Xg6utMzrIDPj2qixCp3XhvYbm/Yjbu8bsV/fdpgweOLevEYMYXNi4QOisLGEnLlnk/lE+HKTxakBzlVwbUI3FPl8Wlbp4aJGZmhUKbZHK5Qg/akk+gb8Wf4hC/sZ3qTtGkqFbhCZiRz4HghDfRvQJ3KoU/OLThQD30MlzUVb7rF31aaBloGeCAfmPPAqCrjQM/iWb/im3ArRz6zGrQoOy5KxjDBV0me/Fiq6uD5EApgpYWTzCpbwmB3HHPPB8xRLszV3GMncSx7uLk6iavggN2Cd4P5TwIDAQAB";
    AlipayConfig alipayConfig = new AlipayConfig();
    alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
    alipayConfig.setAppId("2021005162626299");
    alipayConfig.setPrivateKey(privateKey);
    alipayConfig.setFormat("json");
    alipayConfig.setAlipayPublicKey(alipayPublicKey);
    alipayConfig.setCharset("UTF-8");
    alipayConfig.setSignType("RSA2");
    return alipayConfig;
  }
}
